package com.mzba.easy.weibo.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.db.StatusTimelineEntry;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.ImageThumbnail;
import com.mzba.easy.weibo.util.MyApplication;
import com.mzba.easy.weibo.util.StringUtil;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
/**
 * 
 * @author 06peng
 *
 */
public class NewsActivity extends BasicActivity implements OnClickListener, Callback {
	
	/**1代表发表新微博、2代表转发、3代表评论*/
	private int new_type;
	private String id;
	private String reid;
	/**是否在转发的同时发表评论，0：否、1：评论给当前微博、2：评论给原微博、3：都评论，默认为0 。*/
	private int is_comment = 0;
	private ActionBar actionBar;
	
	private final int menu_add = 1;
	private final int menu_confirm = 2;
	private final int menu_location = 3;
	private final int menu_photo = 4;
	private final int menu_attendtion = 5;
	private final int menu_emotion = 6;
	private final int menu_commentto_author = 7;
	private final int menu_commentto_original = 8;
	private final int menu_retweetto_status = 9;
	
	private boolean isAuthor; //转发：是否评论给作者
	private boolean isOriginal; //转发：是否评论给原微博
	private boolean isRetweet; //评论：是否转发到我的微博
	
	private final int update_status = 1001;
	private final int update_status_error = 1002;
	private final int repost = 1003;
	private final int delete_photo = 1004;
	private final int delete_location = 1005;
	private final int back = 1007;
	private final int comment_status = 10010;
	private final int comment_status_error = 10011;
	private final int reply_comment = 10012;
	private final int reply_comment_error = 10013;
	
	private final int requstcode = 1009;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_pick_with_data = 1008;
	
	
	private EditText editView;
	private ImageView photoView;
	private RelativeLayout photoLayout;
	private TextView locateView;
	private LinearLayout locateLayout;
	
	private LocationClient mLocClient;
	private Handler handler;
	private MyApplication app;
	private WeiboManager manager;
	private boolean isLocate;
	private boolean isUploadPic;
	private File picFile;
	private final static int REQUEST_WIDTH = 1000;
	private WeakReference<Bitmap> bitmapWeak;
	
	private PopupWindow pop;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.news);
		handler = new Handler(this);
		new_type = getIntent().getIntExtra(AppContext.NEWTYPE, 1);
		actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        if (new_type == 1) {
        	actionBar.setTitle("发表新微博");
        } else if (new_type == 2) {
        	actionBar.setTitle("转发微博");
        	id = getIntent().getStringExtra("id");
        	reid = getIntent().getStringExtra("reid");
        } else if (new_type == 3) {
        	id = getIntent().getStringExtra("id");
        	reid = getIntent().getStringExtra("reid");
        	if (StringUtil.isNotBlank(reid)) {
        		actionBar.setTitle("回复评论");
        	} else {
        		actionBar.setTitle("评论微博");
        	}
        }
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
        
        editView = (EditText) findViewById(R.id.news_edit);
        photoView = (ImageView) findViewById(R.id.news_photo);
        photoView.setOnClickListener(this);
        photoLayout = (RelativeLayout) findViewById(R.id.news_photo_layout);
        locateView = (TextView) findViewById(R.id.news_locate_value);
        locateLayout = (LinearLayout) findViewById(R.id.new_location_layout);
        locateLayout.setOnClickListener(this);
        
        app = (MyApplication) getApplication();
        app.setHandler(handler);
		mLocClient = app.mLocationClient;
		manager = new WeiboManager(this);
		
		View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(this);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					editView.append(filed.getPhrase());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menu_add, 0, "插入").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.add(0, menu_confirm, 0, "确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case menu_add:
			startActionMode(new AnActionModeOfNewsProportions());
			break;
		case android.R.id.home:
			if (isUploadPic || isLocate || !editView.getText().toString().trim().equals("")) {
				showChoseMes("确定要返回吗？", back);
			} else {
				finish();
			}
			break;
		case menu_confirm:
			if (editView.getText().toString().trim().equals("")) {
				Toast.makeText(this, "请输入要发表的内容！", Toast.LENGTH_LONG).show();
			} else {
				if (new_type == 1) {
					UICore.eventTask(this, this, update_status, "", null);
				} else if (new_type == 2) {
					UICore.eventTask(this, this, repost, "", null);
				} else if (new_type == 3) {
					if (StringUtil.isNotBlank(reid)) {
						UICore.eventTask(this, this, reply_comment, "", null);
					} else {
						UICore.eventTask(this, this, comment_status, "", null);
					}
				}
			}
			break;
		default:
			break;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		if (v == photoView) {
			showChoseMes("确定要删除该图片吗？", delete_photo);
		} else if (v == locateLayout) {
			showChoseMes("确定要取消定位吗？", delete_location);
		}
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == delete_photo) {
			isUploadPic = false;
			photoView.setImageBitmap(null);
			photoLayout.setVisibility(View.GONE);
		} else if (what == delete_location) {
			isLocate = false;
			locateLayout.setVisibility(View.GONE);
		} else if (what == back) {
			finish();
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case update_status:
			StatusTimelineEntry entry = null;
			if (isUploadPic) {
				if (isLocate) {
					entry = manager.uploadStatus(editView.getText().toString().trim(), app.getLatitude(), app.getLongitude(), picFile);
				} else {
					entry = manager.uploadStatus(editView.getText().toString().trim(), 0.0, 0.0, picFile);
				}
			} else {
				if (isLocate) {
					entry = manager.updateStatus(editView.getText().toString().trim(), app.getLatitude(), app.getLongitude());
				} else {
					entry = manager.updateStatus(editView.getText().toString().trim(), 0.0, 0.0);
				}
				
			}
			if (entry != null) {
				handler.sendEmptyMessage(update_status);
			} else {
				handler.sendEmptyMessage(update_status_error);
			}
			break;
		case repost:
			if (isAuthor && isOriginal) {
				is_comment = 3;
			} else if (isAuthor) {
				is_comment = 1;
			} else if (isOriginal) {
				is_comment = 2;
			} else {
				is_comment = 0;
			}
			StatusTimelineEntry entry2 = manager.repost(editView.getText().toString().trim(), id, is_comment);
			if (entry2 != null) {
				handler.sendEmptyMessage(repost);
			} else {
				handler.sendEmptyMessage(update_status_error);
			}
			break;
		case comment_status:
			CommentEntry commentEntry = manager.commentStatus(editView.getText().toString().trim(), id, isRetweet == true ? 1 : 0);
			if (commentEntry != null) {
				handler.sendEmptyMessage(comment_status);
			} else {
				handler.sendEmptyMessage(comment_status_error);
			}
			break;
		case reply_comment:
			CommentEntry commentEntry2 = manager.replayCommemnt(editView.getText().toString().trim(), id, reid, isRetweet == true ? 1 : 0);
			if (commentEntry2 != null) {
				handler.sendEmptyMessage(reply_comment);
			} else {
				handler.sendEmptyMessage(reply_comment_error);
			}
			break;
		default:
			break;
		}
	}
	
	private final class AnActionModeOfNewsProportions implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            //Used to put dark icons on light action bar
        	if (new_type == 1) {
        		menu.add(0, menu_location, 0, "定位").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                menu.add(0, menu_photo, 0, "照片").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                menu.add(0, menu_attendtion, 0, "@").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                menu.add(0, menu_emotion, 0, "表情").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        	} else if (new_type == 2) {
        		MenuItem menuItem = menu.add(0, menu_commentto_author, 0, "评论给作者");
        		menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        		menuItem.setCheckable(true);
        		if (isAuthor) {
        			menuItem.setChecked(true);
        		} else {
        			menuItem.setChecked(false);
        		}
        		if (StringUtil.isNotBlank(reid)) {
        			MenuItem menuItem2=  menu.add(0, menu_commentto_original, 0, "评论给原微博").setCheckable(true);
        			menuItem2.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
            		menuItem2.setCheckable(true);
            		if (isOriginal) {
            			menuItem2.setChecked(true);
            		} else {
            			menuItem2.setChecked(false);
            		}
        		}
        		menu.add(0, menu_attendtion, 0, "@").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        		menu.add(0, menu_emotion, 0, "表情").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        	} else if (new_type == 3) {
        		MenuItem menuItem  = menu.add(0, menu_retweetto_status, 0, "转发到我的微博");
        		menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        		menuItem.setCheckable(true);
        		if (isRetweet) {
        			menuItem.setChecked(true);
        		} else {
        			menuItem.setChecked(false);
        		}
        		menu.add(0, menu_attendtion, 0, "@").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                menu.add(0, menu_emotion, 0, "表情").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        	}
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
			case menu_location:
				mode.finish();
				isLocate = true;
				mLocClient.start();
				locateLayout.setVisibility(View.VISIBLE);
				locateView.setText("定位中......");
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				}
				break;
			case menu_photo:
				mode.finish();
				doPickPhotoAction();
				break;
			case menu_attendtion:
				mode.finish();
				Intent intent = new Intent(NewsActivity.this, ChooseFriendActivity.class);
				startActivityForResult(intent, requstcode);
				break;
			case menu_emotion:
				mode.finish();
				if (!pop.isShowing()) {
					pop.showAtLocation(findViewById(R.id.news_layout), Gravity.BOTTOM, 0, 0);
				} else {
					pop.dismiss();
				}
				break;
			case menu_commentto_author:
				if (isAuthor) {
					item.setChecked(false);
					isAuthor = false;
				} else {
					item.setChecked(true);
					isAuthor = true;
				}
				break;
			case menu_commentto_original:
				if (isOriginal) {
					isOriginal = false;
					item.setChecked(false);
				} else {
					isOriginal = true;
					item.setChecked(true);
				}
				break;
			default:
				break;
			}
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
        	
        }
    }

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case AppContext.LOCATE_RESULT:
			try {
				locateView.setText(app.getAddress());
				mLocClient.stop();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case update_status:
			onToast("发表成功！");
			finish();
			break;
		case update_status_error:
			onToast("发表失败！");
			break;
		case repost:
			onToast("转发成功！");
			finish();
			break;
		case comment_status_error:
			onToast("评论失败!");
			finish();
			break;
		case comment_status:
			onToast("评论成功!");
			finish();
			break;
		case reply_comment:
			onToast("回复评论成功");
			break;
		case reply_comment_error:
			onToast("回复评论失败");
			break;
		default:
			break;
		}
		return false;
	}

	private void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.take_photo); // 拍照
		choices[1] = getString(R.string.choose_photo); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.set_photo);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String status = Environment.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							break;
						case 1:
							doSelectImageFromLoacal();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "temp");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			Uri pictureUri = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
			startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从本地手机中选择图片
	 */
	private void doSelectImageFromLoacal() {
		Intent localIntent = new Intent();
		localIntent.setType("image/*");
		localIntent.setAction("android.intent.action.GET_CONTENT");
		Intent localIntent2 = Intent.createChooser(localIntent, getString(R.string.choose_photo));
		startActivityForResult(localIntent2, activity_result_pick_with_data);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case activity_result_pick_with_data: // 从本地选择图片
			if (data == null) {
				return;
			}
			Uri uri = data.getData();
			ContentResolver resolver = getContentResolver();
			try {
				InputStream inputStream1 = resolver.openInputStream(uri);
				InputStream inputStream2 = resolver.openInputStream(uri);
				Bitmap bitmapDecode = ImageThumbnail.decodeStream(inputStream1, inputStream2, REQUEST_WIDTH);
				if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
					bitmapWeak = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
				} else {
					bitmapWeak = new WeakReference<Bitmap>(bitmapDecode);
				}
				File pictureFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "temp");
				if (!pictureFileDir.exists()) {
					pictureFileDir.mkdirs();
				}
				picFile = new File(pictureFileDir, "upload.jpeg");
				if (!picFile.exists()) {
					picFile.createNewFile();
				}
				FileOutputStream ous = new FileOutputStream(picFile);
				bitmapWeak.get().compress(Bitmap.CompressFormat.PNG, 100, ous);
				int width = bitmapWeak.get().getWidth();
				int height = bitmapWeak.get().getHeight();
				Matrix matrix = new Matrix();
				int degree = ImageThumbnail.getExifOrientation(picFile.getAbsolutePath());
				matrix.setRotate(degree);
				System.out.println("------------------------->>>" + degree);
				bitmapWeak = new WeakReference<Bitmap>(Bitmap.createBitmap(bitmapWeak.get(), 0, 0, width, height, matrix, true));
				photoView.setImageBitmap(bitmapWeak.get());
				isUploadPic = true;
				photoLayout.setVisibility(View.VISIBLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_camara_with_data: // 拍照
			try {
				File pictureFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "temp");
				picFile = new File(pictureFileDir, "upload.jpeg");
				if (picFile != null && picFile.length() > 0) {
					InputStream inputStream1 = new FileInputStream(picFile);
					InputStream inputStream2 = new FileInputStream(picFile);
					Bitmap bitmapDecode = ImageThumbnail.decodeStream(
							inputStream1, inputStream2, REQUEST_WIDTH);
					if (bitmapDecode.getWidth() > REQUEST_WIDTH) {
						bitmapWeak = new WeakReference<Bitmap>(ImageThumbnail.getCompressBmp(bitmapDecode, REQUEST_WIDTH, true));
					} else {
						bitmapWeak = new WeakReference<Bitmap>(bitmapDecode);
					}
					int width = bitmapWeak.get().getWidth();
					int height = bitmapWeak.get().getHeight();
					Matrix matrix = new Matrix();
					int degree = ImageThumbnail.getExifOrientation(picFile.getAbsolutePath());
					matrix.setRotate(degree);
					System.out.println("------------------------->>>" + degree);
					bitmapWeak = new WeakReference<Bitmap>(Bitmap.createBitmap(bitmapWeak.get(), 0, 0, width, height, matrix, true));
					pictureFileDir = new File(
							Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
					if (!pictureFileDir.isDirectory()) {
						pictureFileDir.mkdirs();
					}
					picFile = new File(pictureFileDir, "upload.jpeg");
					FileOutputStream ous = new FileOutputStream(picFile);
					bitmapWeak.get().compress(Bitmap.CompressFormat.JPEG, 100, ous);
					photoView.setImageBitmap(bitmapWeak.get());
					isUploadPic = true;
					photoLayout.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case requstcode:
			try {
				if (data != null) {
					String[] friends = data.getStringArrayExtra("friends");
					for (String friend : friends) {
						editView.append("@" + friend + " ");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (bitmapWeak != null && bitmapWeak.get() != null && !bitmapWeak.get().isRecycled()) {
				bitmapWeak.get().recycle();
				bitmapWeak = null;
			}
			if (picFile != null) {
				picFile.delete();
				picFile = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
